#coding=utf8
import uuid 
from core import handle
from ws_setting import core_logger, CUSTOM_OBJ_SESSION_ID_NAME

class Session():
    """
        每一个session对应一个客户端的连接， 使用socket fileno 来区分不同的session， 即session id
    """
    data = ""
    to_sessions = set()
    closed = False #是否已经关闭

    def __init__(self, socket, container, *args, **kwargs):
        self.address, self.port = args
    
        self.app_container = container
        setattr(self, CUSTOM_OBJ_SESSION_ID_NAME, self.create_session_id(socket, args, kwargs))

        self.commands = list()
        custom_handle = kwargs["handle"]  if "handle" in kwargs else None

        self._handle = custom_handle if custom_handle else handle.handshake(socket)

        
        if not self._handle:
            raise RuntimeError("no suitable handle")

        self.obtain_parameters()
        self.register()

        self._fc = self.app_container.get_filterChain()

        self._fc.process(self, method="onopen")

    def create_session_id(self, socket, *args, **kargs):
        """
            create session id
        """
        #        return socket.fileno()
        return str(uuid.uuid4())

    def register(self):
        """
            向socket管理器注册
        """
        self.app_container.add_session(self)

    def cancel(self):
        self.app_container.remove_session(self)

    def close_session(self):
        self.closed = True
        self._handle.close_socket()
        try:
            self.app_container.remove_session(self)
        except:
            pass

    def recv_data(self):
        return self._handle.recv_data()

    def send_data(self, data):
        self._handle.send_data(data)

    def obtain_parameters(self):
        header_info = self._handle.header_info
        """
            从handshake的请求头中获得必要的参数
        """
        self.host = header_info.host
        self.origin = header_info.origin

        self.parameters = header_info.parameters

        core_logger.debug("parameters = {}".format(self.parameters))

        self.context, self.url = header_info.parseUrl()

        if not self.url:
            self.url = "/"

        core_logger.debug("[ path = {} , url = {} ]".format(self.context, self.url))

    def process(self):
        #filter chain start
        self._fc.process(self)

    def clean(self):
        def del_res(name):
            if hasattr(self, name) and getattr(self, name):
                del self.__dict__[name]
        del_res("process_function")
        del_res("data")
        del_res("full_func_str")


    def __eq__(self, session):
        return getattr(self, CUSTOM_OBJ_SESSION_ID_NAME) == getattr(session, CUSTOM_OBJ_SESSION_ID_NAME)
    
